package com.tianji.aigc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tianji.aigc.config.SessionProperties;
import com.tianji.aigc.config.TitlePromptConfig;
import com.tianji.aigc.entity.ChatSession;
import com.tianji.aigc.enums.MessageTypeEnum;
import com.tianji.aigc.mapper.ChatSessionMapper;
import com.tianji.aigc.memory.MyAssistantMessage;
import com.tianji.aigc.service.IChatService;
import com.tianji.aigc.service.IChatSessionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.aigc.vo.ChatSessionVO;
import com.tianji.aigc.vo.MessageVO;
import com.tianji.aigc.vo.SessionVO;
import com.tianji.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 对话session 服务实现类
 * </p>
 *
 * @author bai
 * @since 2025-08-07
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements IChatSessionService {

    private final SessionProperties sessionProperties;
    private final ChatMemory redisChatMemory;

    private final ChatClient titleClient;
    private final TitlePromptConfig titlePromptConfig;

    @Override
    public List<SessionVO.Example> hotExamples(Integer num) {
        return RandomUtil.randomEleList(sessionProperties.getExamples(), num);
    }

    @Override
    public List<MessageVO> queryBySessionId(String sessionId) {
        // 获取对话id
        String conversationId = IChatService.getConversationId(sessionId);
        List<Message> messages = redisChatMemory.get(conversationId);
        return messages.stream()
                // 过滤掉非用户消息和助手消息
                .filter(message -> message.getMessageType() == MessageType.ASSISTANT || message.getMessageType() == MessageType.USER)
                // 转换成MessageVO
                .map(message -> {
                    if (message instanceof AssistantMessage){
                        return MessageVO.builder()
                                .type(MessageTypeEnum.ASSISTANT)
                                .content(message.getText())
                                .params(((MyAssistantMessage) message).getParams())
                                .build();
                    }else {
                        return MessageVO.builder()
                                .type(MessageTypeEnum.valueOf(message.getMessageType().name()))
                                .content(message.getText())
                                .build();
                    }

                })
                .toList();
    }

    @Override
    public SessionVO createSession(Integer num) {

        // 从配置中获取sessionVO
        SessionVO sessionVO = BeanUtil.toBean(sessionProperties, SessionVO.class);
        sessionVO.setExamples(RandomUtil.randomEleList(sessionVO.getExamples(), num));
        sessionVO.setSessionId(IdUtil.fastSimpleUUID());

        // 构建chatSession 对象，并保持到数据库
        ChatSession chatSession = ChatSession.builder()
                .sessionId(sessionVO.getSessionId())
                .userId(UserContext.getUser())
                .build();
        super.save(chatSession);

        return sessionVO;
    }

    /**
     * 异步更新聊天会话的标题
     * @param sessionId 会话ID，用于标识特定的聊天会话
     * @param title     新的会话标题，如果为空则不进行更新
     * @param userId    用户ID
     */
    @Async
    @Override
    public void update(String sessionId, String title, Long userId) {
        // 查询符合条件的会话
        ChatSession chatSession = super.lambdaQuery()
                .eq(ChatSession::getSessionId, sessionId)
                .eq(ChatSession::getUserId, userId)
                .one();
        // 如果聊天会话不存在，则直接返回
        if (chatSession == null){
            return;
        }
        // 如果聊天标题为空，且新标题不为空，则更新会话标题
        if (StrUtil.isEmpty(chatSession.getTitle()) && StrUtil.isNotBlank(title)){
//            chatSession.setTitle(StrUtil.sub(title, 0, 20));
            chatSession.setTitle(generateTitle(title));
        }
        // 设置更新字段为updateTime为当前时间
        chatSession.setUpdateTime(LocalDateTime.now());
        // 更新数据库中的聊天会话信息
        super.updateById(chatSession);
    }

    private String generateTitle(String title) {
        String userText = StrUtil.format("""
                对话内容：
                {}
                """, title);
        return titleClient.prompt()
                .system(titlePromptConfig.getTitleSystemMessage().get())
                .user(userText)
                .call()
                .content();
    }

    /**
     * 查询用户的历史会话
     * @return 用户的会话列表
     */
    @Override
    public Map<String, List<ChatSessionVO>> queryHistorySession() {
        Long userId = UserContext.getUser();
        List<ChatSession> list = super.lambdaQuery()
                .eq(ChatSession::getUserId, userId)
                .isNotNull(ChatSession::getTitle)
                .orderByDesc(ChatSession::getUpdateTime)
                .last("limit 30")
                .list();

        if (CollUtil.isEmpty(list)){
            log.info("No chat sessions found for user: {}", userId);
            return Map.of();
        }
        List<ChatSessionVO> chatSessionVOS = CollStreamUtil.toList(list, chatSession -> ChatSessionVO.builder()
                .sessionId(chatSession.getSessionId())
                .title(chatSession.getTitle())
                .updateTime(chatSession.getUpdateTime())
                .build());

        final var TODAY = "当天";
        final var LAST_30_DAYS = "最近30天";
        final var LAST_YEAR = "最近1年";
        final var MORE_THAN_YEAR = "1年以上";

        LocalDate now = LocalDate.now();
        return CollStreamUtil.groupByKey(chatSessionVOS, chatSessionVO -> {
            long abs = Math.abs(ChronoUnit.DAYS.between(chatSessionVO.getUpdateTime().toLocalDate(), now));
            if (abs < 1) {
                return TODAY;
            } else if (abs <= 30) {
                return LAST_30_DAYS;
            } else if (abs <= 365) {
                return LAST_YEAR;
            } else {
                return MORE_THAN_YEAR;
            }
        });
    }

    /**
     * 删除历史会话
     * @param sessionId 会话ID
     */
    @Override
    public void deleteHistorySession(String sessionId) {
        // 删除数据库中的会话
        LambdaQueryWrapper<ChatSession> wrapper = Wrappers.<ChatSession>lambdaQuery()
                .eq(ChatSession::getSessionId, sessionId)
                .eq(ChatSession::getUserId, UserContext.getUser());
        super.remove(wrapper);

        redisChatMemory.clear(IChatService.getConversationId(sessionId));
    }

    /**
     * 更新会话的标题
     * @param sessionId 会话ID
     * @param title     新的标题
     */
    @Override
    public void updateTitle(String sessionId, String title) {
        super.lambdaUpdate()
                .eq(ChatSession::getSessionId, sessionId)
                .eq(ChatSession::getUserId, UserContext.getUser())
                .set(ChatSession::getTitle, StrUtil.sub(title, 0, 100))
                .update();
    }
}
